﻿/* ----------------------------------------------------------------------------
 * Copyright (c) Rob Ashton 2009
 *
 * This source code is subject to terms and conditions of the Microsoft Public 
 * License (Ms-PL).
 * 
 * By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 * 
 * To request a copy of the Microsoft Public License, send a request by email
 * to license@mvcex.com
 *
 * This notice must not be removed from this software.
 * ---------------------------------------------------------------------------- */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEx.Controllers;
using System.Reflection;
using MvcEx.Configuration;

namespace MvcEx
{
    public class MvcExApplicationControllerBuilderSelector : IMvcExControllerBuilderSelector
    {
        #region Instance Fields

        private IMvcExApplication mApplication;
        private Dictionary<String, IMvcExControllerBuilder> mBuilderCache = new Dictionary<string, IMvcExControllerBuilder>();

        #endregion

        #region .ctor

        public MvcExApplicationControllerBuilderSelector(IMvcExApplication application)
        {
            mApplication = application;
            mApplication.ConfigurationChanged += new EventHandler(mApplication_ConfigurationChanged);
        }

        #endregion

        #region IMvcExControllerBuilderSelector Members

        public IMvcExControllerBuilder GetActiveBuilder()
        {
            // Get the active configuration
            var configuration = mApplication.GetActiveConfiguration();

            IMvcExControllerBuilder builder = null;
            if (!mBuilderCache.TryGetValue(configuration.Id, out builder))
            {
                // Get the builder configuration
                var builderConfiguration = MvcExControllerBuilderConfigurationFactory.CreateBuilderConfigurationFromApplication(mApplication, configuration);

                // And create the builder from that configuration
                builder = new MvcExControllerBuilder(builderConfiguration);

                // And cache it
                mBuilderCache[configuration.Id] = builder;
            }

            // And return the created builder (if there is one)
            return builder;
        }

        #endregion

        #region Event Handlers
        
        void mApplication_ConfigurationChanged(object sender, EventArgs e)
        {
            // Clear the builder cache
            mBuilderCache.Clear();
        }

        #endregion
    }
}
